<template>
  <div class="pay container">
    <!-- 收货地址 -->
    <pay-box :component="UserAddress"
             title="收货地址"/>

    <!-- 商品信息 -->
    <pay-box :component="GoodList"
             title="商品信息"/>

    <!-- 配送时间 -->
    <pay-box title="配送时间">
      <div class="flex-box">
        <xtx-button v-model="deliveryTimeType"
                    :value="1"
                    type="active"
                    width="230px">
          不限送货时间：周一至周日
        </xtx-button>

        <xtx-button v-model="deliveryTimeType"
                    :value="2"
                    type="active"
                    width="230px">
          工作日送货：周一至周五
        </xtx-button>

        <xtx-button v-model="deliveryTimeType"
                    :value="3"
                    type="active"
                    width="230px">
          双休日、假日送货：周六至周日
        </xtx-button>
      </div>
    </pay-box>

    <!-- 支付方式 -->
    <pay-box title="支付方式">
      <div class="flex-box">
        <xtx-button v-model="payType"
                    :value="1"
                    type="active"
                    width="230px">
          在线支付
        </xtx-button>

        <xtx-button v-model="payType"
                    :value="2"
                    type="active"
                    width="230px">
          货到付款
        </xtx-button>

        <div style="color: #999999">货到付款需付5元手续费</div>
      </div>
    </pay-box>

    <!-- 金额明细 -->
    <pay-box title="金额明细">
      <div class="flex-box flex-right">
        <pay-info/>
      </div>
    </pay-box>

    <!-- 提交 -->
    <pay-box>
      <div class="flex-box flex-right submit-box">
        <xtx-button type="submit"
                    @click="submitClick">
          提交订单
        </xtx-button>
      </div>
    </pay-box>
  </div>

  <!-- 切换地址弹出框 -->
  <my-dialog v-model="showChangeAddr"
             :mask-close="false"
             auto>
    <template v-if="cartStore?.address?.length">
      <div v-for="(address, index) in cartStore.address"
           :key="index"
           :class="{active: address === cartStore.defaultAddress}"
           class="address-box">
        <i class="iconfont icon-close-new"
           @click="delAddress(address)"/>
        <address-info :data="address"
                      @click="addressChange(index)"/>
      </div>
    </template>
    <div v-else
         class="empty">
      暂无收货地址，请先添加
    </div>
  </my-dialog>

  <!-- 收货地址填写表单 -->
  <my-dialog v-model="showAddrForm"
             :mask-close="false"
             title="添加收货地址">
    <div style="width: 100%;display:flex; flex-direction: column;align-items: center;">
      <xtx-input ref="nameInput"
                 v-model="addrForm.receiver"
                 :rules="formRule.name"
                 label="收货人："
                 label-width="80px"
                 placeholder="请输入收货人"
                 width="400px"/>
      <xtx-input ref="mobileInput"
                 v-model="addrForm.contact"
                 :rules="formRule.mobile"
                 label="手机号："
                 label-width="80px"
                 placeholder="请输入手机号"
                 width="400px"/>
      <xtx-input ref="mobileInput"
                 v-model="addrForm.contact"
                 label="地区："
                 label-width="80px"
                 width="400px">
        <template #input>
          <city-select :border="false"/>
        </template>
      </xtx-input>
      <xtx-input ref="addrInput"
                 v-model="addrForm.address"
                 :rules="formRule.address"
                 label="详细地址："
                 label-width="80px"
                 placeholder="请输入详细地址"
                 width="400px"/>
      <xtx-input ref="postalCodeInput"
                 v-model="addrForm.postalCode"
                 :rules="formRule.postalCode"
                 label="邮政编码："
                 label-width="80px"
                 placeholder="请输入邮政编码"
                 width="400px"/>
      <xtx-input ref="addressTagsInput"
                 v-model="addrForm.addressTags"
                 :rules="formRule.addressTags"
                 label="地址标签："
                 label-width="80px"
                 placeholder="请输入地址标签"
                 width="400px"/>
      <div style="display: flex;width: 400px;justify-content: space-between">
        <xtx-button type="cancel"
                    width="180px"
                    @click="showAddrForm = false">
          取消
        </xtx-button>
        <xtx-button type="submit"
                    width="180px"
                    @click="addAddressSubmit">
          确认
        </xtx-button>
      </div>
    </div>
  </my-dialog>
</template>

<script lang="ts"
        setup>
import {getAddress} from '@/api/address'
import {submitOrder} from '@/api/cart'
import {formRule} from '@/assets/utils/validate'
import CitySelect from '@/components/library/CitySelect.vue'
import MyDialog from '@/components/library/Dialog/index.vue'
import message from '@/components/library/Message/index'
import XtxButton from '@/components/library/XtxButton.vue'
import XtxInput from '@/components/library/XtxInput.vue'
import {useCartStore} from '@/stores/cart'
import {useCommonStore} from '@/stores/common'
import type {Address} from '@/types/cart'
import type {City} from '@/types/city'
import type {GoodSkuCount} from '@/types/order'
import AddressInfo from '@/views/cart/pay/components/AddressInfo.vue'
import GoodList from '@/views/cart/pay/components/GoodList.vue'
import PayBox from '@/views/cart/pay/components/PayBox.vue'
import PayInfo from '@/views/cart/pay/components/PayInfo.vue'
import UserAddress from '@/views/cart/pay/components/UserAddress.vue'
import {provide, ref, watch} from 'vue'
import {useRouter} from 'vue-router'

let commonStore = useCommonStore()
commonStore.pathList = [commonStore.pathList[0], {name: '购物车', path: '/cart'}, {name: '填写订单', path: ''}]
let cartStore = useCartStore()
let router = useRouter()

let deliveryTimeType = ref<number>(1)
let payType = ref<number>(1)

let showChangeAddr = ref<boolean>(false)
let showAddrForm = ref<boolean>(false)
provide('showChangeAddr', showChangeAddr)
provide('showAddrForm', showAddrForm)

let addrForm = ref<Address>({
  address: '',
  addressTags: '',
  cityCode: '',
  contact: '',
  countyCode: '',
  fullLocation: '',
  isDefault: 0,
  postalCode: '',
  provinceCode: '',
  receiver: ''
})
let cities = ref<City[]>([])
watch<City[]>(() => cities.value, (v: City[]) => {
  addrForm.value.provinceCode = (v[0]?.code ?? '') + ''
  addrForm.value.cityCode = (v[1]?.code ?? '') + ''
  addrForm.value.countyCode = (v[2]?.code ?? '') + ''
  addrForm.value.fullLocation = v.map(i => i.name).join('') + addrForm.value.address
}, {deep: true})
provide('address', cities)

~function requestAll() {
  Promise.all([
    getAddress()
  ]).then(([AddressRes]) => {
    initAddress(AddressRes)
  })
}()

function initAddress(res: any) {
  if (res.code) return
  cartStore.address = res.result.reverse() ?? []
}

async function addressChange(index: number) {
  let obj = cartStore.defaultAddress
  let res = false
  if (obj) {
    if (obj === cartStore.address[index]) return
    // 如果存在旧的默认地址，移除旧的
    obj.isDefault = 0
    res = await cartStore.updateAddress(obj, false)
    if (!res) return message.error('设置默认收货地址失败')
  }
  cartStore.address[index].isDefault = 1
  await cartStore.updateAddress(cartStore.address[index])
  message.success('设置默认收货地址成功')
}

// 提交收货地址
async function addAddressSubmit() {
  if (!addrForm.value.provinceCode) return message.error('请选择地区')
  // TODO 此处应对表单各选项进行校验
  let res = await cartStore.addAddress(addrForm.value)
  if (!res) return message.error('提交失败')
  message.success('提交成功')
  showAddrForm.value = false
}

async function delAddress(addr: Address) {
  let res = await cartStore.delAddress(addr)
  if (!res) return message.error('删除收货地址失败')
  message.success('删除收货地址成功')
}

async function submitClick() {
  if (!cartStore.defaultAddress) return message.error('您还未选择收货地址')
  let res = await submitOrder({
    addressId: cartStore.defaultAddress.id ?? '',
    buyerMessage: '',
    deliveryTimeType: deliveryTimeType.value,
    goods: cartStore.esList.map(i => ({skuId: i.skuId, count: i.count})) as GoodSkuCount[],
    payChannel: 1,
    payType: payType.value
  })
  if (res.code) return message.error('订单提交失败')
  message.success('订单提交成功，即将跳转支付页')
  await router.push(`/cart/pay/pay_page?orderId=${res.result.id}`)
}
</script>

<style lang="less"
       scoped>
.pay {
  margin-bottom: 20px;

  .submit-box {
    padding: 40px;
  }

  .flex-box {
    padding-right: 70px;
    display: flex;
    align-items: center;

    > * ~ * {
      margin-left: 20px;
    }
  }

  .flex-right {
    justify-content: flex-end;
  }
}

.address-box {
  border: 1px solid #f5f5f5;
  border-radius: 4px;
  padding: 10px;
  cursor: pointer;

  i {
    float: right;
    cursor: pointer;

    &:hover {
      color: #CF4444;
    }
  }

  &:hover, &.active {
    border-color: @xtxColor;
    background-color: rgba(@xtxColor, .2);
  }

  & ~ .address-box {
    margin-top: 15px;
  }
}

.empty {
  width: 100%;
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>